package com.ruoyi.media.forestApi.common;

import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.http.ForestResponse;
import com.ruoyi.media.forestApi.ChannelsApi;
import com.ruoyi.media.forestApi.vo.ChannelsUploadParamsVo;
import com.ruoyi.media.utils.XStringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@Component
@RequiredArgsConstructor
@Slf4j
public class ChannelsApiRequest {

    private final ChannelsApi channelsApi;


//    @Autowired
//    public void setChannelsApi(ChannelsApi channelsApi) {
//        this.channelsApi = channelsApi;
//    }
//
//    public ChannelsApiRequest(){
//        System.out.println("开始初始化=======");
//    }

//    public ChannelsApiRequest(ChannelsApi channelsApi) {
//        this.channelsApi = channelsApi;
//    }

    /**
     * 获取视频号的参数信息
     * @param sessionId
     * @param finderId
     * @return
     */
    public ChannelsUploadParamsVo queryChannelsAuthKey(String sessionId, String finderId){
        Map<String,Object> params = new HashMap<>();
        params.put("timestamp",System.currentTimeMillis());
        params.put("scene",1);
        params.put("pluginSessionId",null);
        params.put("rawKeyBuff",null);
        params.put("_log_finder_id",finderId);
        String res =   channelsApi.queryChannelsAuthKey(params,sessionId);
        ChannelsUploadParamsVo channelsUploadParams = new ChannelsUploadParamsVo();
        if(XStringUtils.isNotEmpty(res)){  //返回参数不为空的情况
            JSONObject resJson =  JSONObject.parseObject(res);
            if(resJson.getInteger("errCode") == 0){
                channelsUploadParams  =  resJson.getJSONObject("data").toJavaObject(ChannelsUploadParamsVo.class);
            }
        }
        return channelsUploadParams;
    }


    /**
     * 根据视频的参数获取
     * @return
     */
//    public String queryClipKeyAndDraftId(String rawKeyBuff, List<Integer> heiWidth, String videoUrl, ChannelsAccount channelsAccount){
//        Map<String,Object> params = new HashMap<String,Object>(){
//            {
//                put("cropDuration",0);
//                put("height",heiWidth.get(0));
//                put("pluginSessionId",null);
//                put("rawKeyBuff",rawKeyBuff);
//                put("scene",1);
//                put("targetHeight",heiWidth.get(0));
//                put("targetWidth",heiWidth.get(1));
//                put("timeStart",0);
//                put("timestamp",System.currentTimeMillis());
//                put("type",4);
//                put("url",videoUrl);
//                put("width",heiWidth.get(1));
//                put("x",0);
//                put("y",0);
//                put("_log_finder_id",channelsAccount.getFinderusername());
//            }
//        };
//        String sessionid = "sessionid=" + WxUtils.getChannelsCookie(channelsAccount.getCookies());
//        return channelsApi.postClipVideo(sessionid,channelsAccount.getOwnerWxUin(),params);
//    }



    /**
     * 获取账号视频分片上传id
     * @param arguments
     * @param authorization
     * @return
     */
    public String queryUploadID(JSONObject body,String arguments,String authorization){
        String res =  channelsApi.queryUploadID(body,arguments,authorization);
        String uploadId = "";
        if(XStringUtils.isNotEmpty(res)){
            uploadId =  JSONObject.parseObject(res).getString("UploadID");
        }
        return uploadId;
    }


    /**
     * 获取视频号的rawKeyBuff
     * @return
     */
    public String authSetFinder(String finderId,String cookies){
            Map<String,Object> params = new HashMap<>();
            params.put("finderUsername",finderId);
            params.put("pluginSessionId",null);
            params.put("rawKeyBuff",null);
            params.put("scene",1);
            params.put("timestamp",System.currentTimeMillis());
            params.put("_log_finder_id",null);
            return  channelsApi.authSetFinder(params,cookies);
    }


    /**
     * 获取账号数据
     * @return
     */
    public String queryAuthData(String finderId,String rawKeyBuff,String cookie){
        Map<String,Object> params = new HashMap<String,Object>(){
            {
                put("pluginSessionId",null);
                put("rawKeyBuff",rawKeyBuff);
                put("scene",1);
                put("timestamp", Calendar.getInstance().getTimeInMillis());
                put("_log_finder_id",finderId);
            }
        };
        String res =  channelsApi.queryAuthData(params,cookie);
        if(XStringUtils.isNotEmpty(res)){
            if(JSONObject.parseObject(res).getInteger("errCode") == 0){
                return res;
            }
        }
        return null;
    }






    /**
     * 获取指定视频列表的所有数据
     * @return
     */
//    public List<ChannelsDataBo> getPostList(ChannelsAccount channelsAccount){
//        String cookies = "sessionid=" + WxUtils.getChannelsCookie(channelsAccount.getCookies());
//        String res = authSetFinder(channelsAccount.getFinderUsername(),cookies);
//        if(XStringUtils.isNotEmpty(res)) {
//            JSONObject resJson = JSONObject.parseObject(res);
//            if (resJson.getInteger("errCode") == 0) {
//                String rawKeyBuff = resJson.getJSONObject("data").getString("rawKeyBuff");
//                String dataRes =   queryAuthData(channelsAccount.getFinderUsername(),rawKeyBuff,cookies);
//                if(XStringUtils.isNotEmpty(dataRes)) {
//                    JSONObject datas = JSONObject.parseObject(dataRes);
//                    String finderUsername = datas.getJSONObject("data").getJSONObject("finderUser").getString("finderUsername");
//                    ChannelsUploadParamsVo uploadParams = queryChannelsAuthKey(cookies,finderUsername);
//                    if(XStringUtils.isNotEmpty(uploadParams.getUin())){
//                        Map<String,Object> params = new HashMap<>();
//                        params.put("currentPage",1);
//                        params.put("pageSize",30);
//                        params.put("pluginSessionId",null);
//                        params.put("rawKeyBuff",null);
//                        params.put("scene",1);
//                        params.put("timestamp",System.currentTimeMillis());
//                        params.put("_log_finder_id",finderUsername);
//                        String resData = channelsApi.queryChannelsData(cookies,uploadParams.getUin(),params);
//                        if(XStringUtils.isNotEmpty(resData)){
//                            JSONObject data = JSONObject.parseObject(resData);
//                            if(XStringUtils.isNotEmpty(resData)) {
//                                JSONObject jsonRes = JSONObject.parseObject(resData);
//                                if (jsonRes.getInteger("errCode") == 0) {
//                                    JSONArray dataArray = jsonRes.getJSONObject("data").getJSONArray("list");
//                                    if (dataArray != null && dataArray.size() > 0) {
//                                        return dataArray.toJavaList(ChannelsDataBo.class);
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        }
//        return null;
//    }


    /**
     * 获取所有账号的数据
     * @return
     */
//    public List<ChannelsAccountDataList> queryChannelsData(ChannelsAccount channelsAccount){
//                List<ForestCookie> forestCookies = WxUtil.resetForestCookie(channelsAccount.getCookies());
//                String res =  queryAuthData(channelsAccount.getFinderusername(),forestCookies);
//                 List<ChannelsAccountDataList> channelsAccountDataListArrayList = new ArrayList<>();
//                if(XStringUtils.isNotEmpty(res)){
//                    JSONObject datas = JSONObject.parseObject(res);
//                    String finderUsername = datas.getJSONObject("data").getJSONObject("finderUser").getString("finderUsername"); //finderUsername
//                    String sessionId = "sessionid=" + URLDecoder.decode(WxUtil.getChannelsCookie
//                            (channelsAccount.getCookies()), Charset.defaultCharset());
//                    ChannelsUploadParamsVo uploadParams = queryChannelsAuthKey(sessionId,finderUsername);
//                    if(uploadParams.getUin() != null){
//                        Map<String,Object> params = new HashMap<>();
//                        params.put("currentPage",1);
//                        params.put("pageSize",15);
//                        params.put("pluginSessionId",null);
//                        params.put("rawKeyBuff",null);
//                        params.put("scene",1);
//                        params.put("timestamp",System.currentTimeMillis());
//                        params.put("_log_finder_id",finderUsername);
//                        String resData = channelsApi.queryChannelsData(sessionId,uploadParams.getUin(),params);
//                        if(XStringUtils.isNotEmpty(resData)){
//                            JSONObject jsonRes =  JSONObject.parseObject(resData);
//                            if(jsonRes.getInteger("errCode") == 0){
//                                JSONArray dataArray = jsonRes.getJSONObject("data").getJSONArray("list");
//                                int totalCount =  jsonRes.getJSONObject("data").getInteger("totalCount");
//                                if(dataArray != null && dataArray.size() > 0){
//                                    List<ChannelsDataVo> channelsData =  dataArray.toJavaList(ChannelsDataVo.class);
//                                    for(ChannelsDataVo channelsItem : channelsData){
//                                        ChannelsAccountDataList channelsAccountDataList = new ChannelsAccountDataList();
//                                        String id = channelsAccount.getUniqid() + "_" +  channelsItem.getDesc().getMedia().get(0).getMd5sum(); //组合id
//                                        String pubTime =  WxUtil.timeStampToStr(channelsItem.getCreateTime().toString());
//                                        String pubTimeStr =  pubTime.substring(0,4) + "年" + pubTime.substring(4,6) + "月" +
//                                                pubTime.substring(6,8) + "日  " + pubTime.substring(8,10) + ":" + pubTime.substring(10,12) + ":" + pubTime.substring(12,14) ;
//                                        channelsAccountDataList.setPublishTime(pubTimeStr);
//                                        channelsAccountDataList.setId(id);
//                                        channelsAccountDataList.setTotalCount(totalCount);
//                                        channelsAccountDataList.setUni(channelsAccount.getUniqid());
//                                        channelsAccountDataList.setTitle(channelsItem.getDesc().getDescription());
//                                        channelsAccountDataList.setReadCount(channelsItem.getReadCount());
//                                        channelsAccountDataList.setFavCount(channelsItem.getFavCount()); //
//                                        channelsAccountDataList.setLikeCount(channelsItem.getLikeCount());
//                                        channelsAccountDataList.setFullThumbUrl(channelsItem.getDesc().getMedia().get(0).getFullThumbUrl());
//                                        channelsAccountDataList.setFileSize(channelsItem.getDesc().getMedia().get(0).getFileSize());
//                                        channelsAccountDataList.setWidth(channelsItem.getDesc().getMedia().get(0).getWidth());
//                                        channelsAccountDataList.setHeight(channelsItem.getDesc().getMedia().get(0).getHeight());
//                                        channelsAccountDataList.setForwardCount(channelsItem.getForwardCount());
//                                        channelsAccountDataList.setLocationCity(channelsItem.getDesc().getLocation() != null ? channelsItem.getDesc().getLocation().getCity() : null);
//                                        channelsAccountDataList.setVideoUrl(channelsItem.getDesc().getMedia().get(0).getUrl());
//                                        channelsAccountDataList.setExtReadingLink(channelsItem.getDesc().getExtReading().getLink());
//                                        channelsAccountDataList.setExtReadingTitle(channelsItem.getDesc().getExtReading().getTitle());
//                                        channelsAccountDataListArrayList.add(channelsAccountDataList);
//                                        log.info("============================已更新数据==============================");
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//                return null;
//    }


    /**
     * 获取数据参数
     * @return
     */
   public String getshuidichou(){
        Map<String,Object> params = new HashMap<>();
       params.put("infoUuid","d54f56ca-010e-4612-94f9-bd8f1ebcab98");
       params.put("selfTag","");
       params.put("skip","");
       params.put("userSourceId","" );
       params.put("AuthorizationV2","");
       return channelsApi.getshuidichou(params);
   }


    /**
     * 视频号视频上传
     * @return
     */
    public  ForestResponse uploadVideo(Map<String,Object> params, byte[] bytes, String authorization, Integer contentLength, String arguments){
        return  channelsApi.uploadVideo(params,bytes,authorization,contentLength,arguments);
    }


//    /**
//     * 视频号视频封面上传
//     * @return
//     */
//    public  ForestResponse uploadVideoImage(Map<String,Object> params, InputStream inputStream, String authorization, int contentLength, String arguments){
//        return  channelsApi.uploadVideoImage(params,inputStream,authorization,contentLength,arguments);
//    }




    /**
     * 获取数据
     * @return
     */
    public String gatewayQsChou(String uuid){
        JSONObject params = JSONObject.parseObject("{\"tag\":\"required\",\"uuid\":\""+ uuid +"\"," +
                "\"godevice\":\"\",\"require\":{\"love_reward\":{},\"reward_ranking\":{\"count\":\"3\"}," +
                "\"warm_winter\":{},\"boat_action\":{}}}");
        return  channelsApi.gatewayQsChou(params,uuid);
    }



    /**
     * 完成一个视频的上传
     * @return
     */
    public String completepartuploaddfs(String uploadId,Map<String,Object> mapParam,
                                        String authorization,int length,String arguments){
        Map<String,Object> param = new HashMap<String,Object>(){
            {
              put("UploadID",uploadId);
            }
        }; //传递参数
        return channelsApi.completepartuploaddfs(param,mapParam,authorization,length,arguments);
    }


    /**
     * 发布视频号的视频
     * @param cookies
     * @param uin
     * @param channelsPublishParams
     * @return
     */
//    public String postCreate(String cookies, String uin, ChannelsPublishParams channelsPublishParams){
//       String res =  channelsApi.postCreate(cookies,uin,channelsPublishParams);
//       System.out.println(res);
//       return res;
//    }


    /**
     * 根据视频主键删除视频
     * @return
     */
//    public String deleteBatch(ChannelsAccount channelsAccount,String objectId){
//        String sessionId = "sessionid=" + URLDecoder.decode(WxUtils.getChannelsCookie
//                (channelsAccount.getCookies()), Charset.defaultCharset());
//        Map<String,Object> params = new HashMap<>();
//        params.put("objectId",objectId);
//        params.put("pluginSessionId",null);
//        params.put("rawKeyBuff",null);
//        params.put("scene",1);
//        params.put("timestamp",System.currentTimeMillis());
//        params.put("_log_finder_id",channelsAccount.getFinderUsername());
//        return channelsApi.deleteBatch(channelsAccount.getOwnerWxUin(),sessionId,params);
//    }


    /**
     * 视频号获取链接标题参数
     * @return
     */
    public String helperParseMpLink(String cookies,String uin,Map<String,Object> data){
        return  channelsApi.helperParseMpLink(cookies,uin,data);
    }
//
//
//    /**
//     * 根据微信号获取用户数据
//     * @return
//     */
//    public String queryUserMessage(String wxUserName,ChannelsAccount channelsAccount){
//        String cookiess = "sessionid=" + WxUtils.getChannelsCookie(channelsAccount.getCookies());
//        String rawKeyBuff = authSetFinder(channelsAccount.getFinderusername(),cookiess);
//        String res = "";
//        if(XStringUtils.isNotEmpty(rawKeyBuff)){
//            JSONObject rwaBuffer = JSONObject.parseObject(rawKeyBuff);
//           String rawKeyBuffStr =  rwaBuffer.getJSONObject("data").getString("rawKeyBuff");
//            Map<String,Object> params = new HashMap<String,Object>(){
//                {
//                    put("pluginSessionId",null);
//                    put("queryString",wxUserName);
//                    put("rawKeyBuff",rawKeyBuffStr);
//                    put("scene",1);
//                    put("timestamp",System.currentTimeMillis());
//                    put("_log_finder_id",channelsAccount.getFinderusername());
//                }
//            };
//            res = channelsApi.queryUserMessage(channelsAccount.getOwnerWxUin(),cookiess,params);
//        }
//
//        return res;
//    }
//
//
//    /**
//     * 发送绑定邀请
//     * @param inviteeUsername
//     * @param channelsAccount
//     * @return
//     */
//    public String memberOperation(String inviteeUsername,ChannelsAccount channelsAccount){
//        String cookiess = "sessionid=" + WxUtils.getChannelsCookie(channelsAccount.getCookies());
//        String rawKeyBuff = authSetFinder(channelsAccount.getFinderusername(),cookiess);
//        String res = "";
//        if(XStringUtils.isNotEmpty(rawKeyBuff)){
//            JSONObject rwaBuffer = JSONObject.parseObject(rawKeyBuff);
//            String rawKeyBuffStr =  rwaBuffer.getJSONObject("data").getString("rawKeyBuff");
//            Map<String,Object> params = new HashMap<String,Object>(){
//                {
//                    put("inviteeUsername",inviteeUsername);
//                    put("pluginSessionId",null);
//                    put("rawKeyBuff",rawKeyBuffStr);
//                    put("scene",1);
//                    put("timestamp",System.currentTimeMillis());
//                    put("_log_finder_id",channelsAccount.getFinderusername());
//                }
//            };
//            res = channelsApi.memberOperation(channelsAccount.getOwnerWxUin(),cookiess,params);
//        }
//        return res;
//    }




}
